package HashTable;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class _559_MinimumIndexSumofTwoLists {
    //solution 1:use hashMap
    //focus:many restaurants have the same sum;the sum in loop may be smaller,if that,clear the previous map
    public String[] findRestaurant(String[] list1, String[] list2) {
        Map<String, Integer> map1 = new HashMap<>();
        Map<String, Integer> map2 = new HashMap<>();
        for(int i=0;i<list1.length;i++) {
            map1.put(list1[i],i);
        }
        for(int i=0;i<list2.length;i++) {
            map2.put(list2[i], i);
        }
        int minSum = Integer.MAX_VALUE;
        List<String> result = new ArrayList<>();
        for(Map.Entry<String,Integer> m:map1.entrySet()){
            if (map2.containsKey(m.getKey())) {
                int tempSum = m.getValue() + map2.get(m.getKey());
                if (tempSum < minSum) {
                    result.clear();
                    minSum = tempSum;
                    result.add(m.getKey());
                } else if (tempSum == minSum) {
                    result.add(m.getKey());
                }
            }
        }
        return result.toArray(new String[]{});
    }
}
